package com.leinao.dataset.controller;

import com.alibaba.fastjson.JSON;
import com.leinao.commons.Response;
import com.leinao.config.EnvironmentConfig;
import com.leinao.constant.Constant;
import com.leinao.constant.DataSetEnum;
import com.leinao.constant.LoginEnum;
import com.leinao.dataset.dto.*;
import com.leinao.dataset.service.DataSetService;
import com.leinao.util.page.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author  wangshoufa 
 * @date 2018年11月7日 下午4:54:59
 *
 */
@RestController
@CrossOrigin
public class DataSetController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private DataSetService dataSetService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private EnvironmentConfig env;
	
	@ApiOperation(value="获取数据集", notes="返回数据集列表")
    @GetMapping(value = "/dataSet")
	public Response<PageInfo> getDataSet(
			@ApiParam(value = "当前页", required = false) @RequestParam(required = false) Integer cp,
			@ApiParam(value = "每页条数", required = false) @RequestParam(required = false) Integer ps) {
		cp = null == cp ? Constant.DEFAULT_PAGE_NUMBER : cp;
		ps = null == ps ? Constant.DATASET_LIST_DEFAULT_PAGE_SIZE : ps;
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
		}
		return dataSetService.getDataSetInfo(userInfo.getUserId(), cp, ps);
	}

	@ApiOperation(value="数据集上传", notes="上传数据集")
    @PostMapping(value = "/dataSet")
	@ApiImplicitParam(name = "dataSet", value = "dataSet", required = true, dataType = "PaiDataSetDto")
	public Response<Long> pushDataSet(HttpServletRequest request,
			@ApiParam(value = "数据集填写的信息", required = true) @RequestBody(required = true) PaiDataSetDto dataSet,
			@ApiParam(value = "示例照片ID,多张以,分割", required = false) @RequestParam(required = false) String id) {
		logger.info(String.format("pushDataSet param: {}, picture ids: {}", dataSet, id));
		if(dataSet == null || StringUtils.isBlank(dataSet.getPath())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.PUSH_DATASET_PARAM_ERROR.getSeq(), DataSetEnum.PUSH_DATASET_PARAM_ERROR.getDesc(), null);
		}
		try {
			request.setCharacterEncoding(Constant.CHARACTER_ENCODING);
			return dataSetService.pushDataSet(request, dataSet, id);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}


	@ApiOperation(value="公开数据集", notes="公开数据集")
	@PostMapping(value = "/dataSet/openDataSet")
	@ApiImplicitParam(name = "dataSet", value = "dataSet", required = true, dataType = "publicDataSetDto")
	public Response<Void> openDataSet(@RequestBody PublicDataSetDto publicDataSetDto){
		logger.info("openDataSet param: {}", publicDataSetDto);

		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.openDataSet(userInfo.getUserId(), publicDataSetDto);
	}

	@ApiOperation(value="获取公开数据集列表信息", notes="返回公开数据集列表")
	@GetMapping(value = "/dataSet/publicDataSetList")
	public Response<PageInfo> getPublicDataSetList(@ApiParam(value = "当前页") @RequestParam(required = false) Integer pageNumber,
												   @ApiParam(value = "每页条数") @RequestParam(required = false) Integer pageSize,
												   @ApiParam(value = "分类ID") @RequestParam(required = false) Long categoryId) {
		logger.info("getPublicDataSetList param: pageNumber is {}, pageSize is {}, categoryId is {}", pageNumber, pageSize, categoryId);

		// 默认分页条件设置
		if(pageNumber == null || pageNumber < Constant.DEFAULT_PAGE_NUMBER) {
			pageNumber = Constant.DEFAULT_PAGE_NUMBER;
		}
		if(pageSize == null || pageSize < Constant.DEFAULT_PAGE_NUMBER) {
			pageSize = Constant.DEFAULT_PAGE_SIZE;
		}

		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.getPublicDataSetList(categoryId, userInfo.getUserId(), pageNumber, pageSize);
	}
	
	@ApiOperation(value="数据集列表", notes="项目创建时选择的数据集列表,包括公开数据集、个人私有数据集、被分享的数据集")
	@GetMapping(value = "/optionalDataSet")
	public Response<List<PaiDataSetDto>> optionalDataSet(@ApiParam(value = "搜索内容") @RequestParam(required = false) String search,
											HttpServletRequest request) {
		logger.info("optionalDataSet param: search is {}", search);
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}
		return dataSetService.optionalDataSet(search, userInfo);
	}
	
	@ApiOperation(value="数据集数据集明细", notes="数据集明细")
	@GetMapping(value = "/dataSetDetail")
	public Response<PaiDataSetDto> dataSetDetail(HttpServletRequest request,
			@ApiParam(value = "当前数据集的编号", required = true) @RequestParam(required = true) String number) {
		logger.info("dataSetDetail param: number is {}", number);
		String obj = (String) request.getSession().getAttribute("userInfo");
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
		}
		return dataSetService.dataSetDetail(userInfo.getUserId(), number);
	}

	@ApiOperation(value="数据集共享人员信息", notes="返回数据集共享人员信息")
	@GetMapping(value = "/dataSet/getDataSetSharingUser")
	public Response<DataSetSharingUserDto> getDataSetSharingUser(@ApiParam(value = "数据集ID", required = true) @RequestParam Long datasetId) {
		logger.info("getDataSetSharingUser param: datasetId is {}", datasetId);

		// 获取用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.getDataSetSharingUser(datasetId, userInfo);
	}

	@ApiOperation(value="获取邮箱对应的用户信息", notes="返回邮箱对应的用户信息")
	@GetMapping(value = "/dataSet/getSharingUserInfo")
	public Response<UserInfoDto> getSharingUserInfo(@ApiParam(value = "用户邮箱", required = true) @RequestParam String email) {
		logger.info("getSharingUserInfo param: email is {}", email);

		// 获取用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.getSharingUserInfo(email, userInfo);
	}

	@ApiOperation(value="获取项目数据集列表", notes="获取项目数据集列表")
	@GetMapping(value = "/dataSet/getProjectDataSetList")
	public Response<List<PaiDataSetDto>> getProjectDataSetList(@ApiParam(value = "项目ID") @RequestParam Long projectId) {
		logger.info("getProjectDataSetList param: projectId is {}", projectId);
		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.getProjectDataSetList(projectId, userInfo.getUserId());
	}

	@ApiOperation(value="搜索公开数据集列表信息", notes="搜索公开数据集列表")
	@GetMapping(value = "/dataSet/searchPublicDataSetList")
	public Response<PageInfo> searchPublicDataSetList(@ApiParam(value = "当前页") @RequestParam(required = false) Integer pageNumber,
													  @ApiParam(value = "每页条数") @RequestParam(required = false) Integer pageSize,
													  @ApiParam(value = "搜索内容") @RequestParam String search) {
		logger.info("searchPublicDataSetList param: pageNumber is {}, pageSize is {}, search: {}", pageNumber, pageSize, search);

		// 默认分页条件设置
		if(pageNumber == null || pageNumber < Constant.DEFAULT_PAGE_NUMBER) {
			pageNumber = Constant.DEFAULT_PAGE_NUMBER;
		}
		if(pageSize == null || pageSize < Constant.DEFAULT_PAGE_NUMBER) {
			pageSize = Constant.DEFAULT_PAGE_SIZE;
		}

		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );

		return dataSetService.searchPublicDataSetList(search, userInfo.getUserId(), pageNumber, pageSize);
	}
	
	/**
	  * @Description 	关注/取消关注数据集
	  * @param attentionFlag	关注/取消关注标记  0:取消关注	1:关注
	  * @param dataSetId	数据集Id
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/15 16:22
	  */
	@ApiOperation(value="关注/取消关注数据集", notes="关注/取消关注数据集")
	@GetMapping(value = "/dataSet/attentionDataSet")
	public Response<Void> attentionDataSet(@ApiParam(value = "关注/取消关注标记") @RequestParam(required = true) Integer attentionFlag,
													  @ApiParam(value = "数据集Id") @RequestParam(required = true) Long dataSetId) {
		logger.info("searchPublicDataSetList param: attentionFlag is {}, dataSetId is {}", attentionFlag, dataSetId);

		if(dataSetId == null){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getDesc(), null);
		}
		if(attentionFlag == null){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ATTENTION_FLAG_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ATTENTION_FLAG_EMPTY_ERROR.getDesc(), null);
		}

        if((!attentionFlag.equals(Constant.DATASET_NO_ATTENTION)) && (!attentionFlag.equals(Constant.DATASET_IS_ATTENTION))){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ATTENTION_FLAG_IS_ERROR.getSeq(),
					DataSetEnum.DATASET_ATTENTION_FLAG_IS_ERROR.getDesc(), null);
		}

		// 获取登录用户信息
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
		}

		return dataSetService.attentionDataSet(dataSetId, attentionFlag, userInfo);
	}
	
	/**
	  * @Description 	获取我的数据集列表(用户所有和用户关注的)
	  * @param pageNumber	当前页数
	  * @param pageSize		每页展示条数
	  * @param dataSetType	数据集类型	0:我上传的  1:我关注的
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/15 16:22
	  */
	@ApiOperation(value="获取数据集", notes="返回数据集列表")
	@GetMapping(value = "/getUserDataSet")
	public Response<PageInfo> getUserDataSet(
			@ApiParam(value = "当前页", required = false) @RequestParam(required = false) Integer pageNumber,
			@ApiParam(value = "每页条数", required = false) @RequestParam(required = false) Integer pageSize,
			@ApiParam(value = "数据集类型", required = false) @RequestParam(required = false) Integer dataSetType) {

		logger.info("getUserDataSet param: pageNumber is {}, pageSize is {}, dataSetType is {}", pageNumber, pageSize, dataSetType);
		// 默认分页条件设置
		if(pageNumber == null || pageNumber < Constant.DEFAULT_PAGE_NUMBER) {
			pageNumber = Constant.DEFAULT_PAGE_NUMBER;
		}
		if(pageSize == null || pageSize < Constant.DEFAULT_PAGE_NUMBER) {
			pageSize = Constant.DEFAULT_PAGE_SIZE;
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj,LoginResultDto.class );
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
		}

		if(null != dataSetType && dataSetType != Constant.USER_UPLOAD_DATASET && dataSetType != Constant.USER_ATTENTION_DATASET ){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_TYPE_FLAG_IS_ERROR.getSeq(),
					DataSetEnum.DATASET_TYPE_FLAG_IS_ERROR.getDesc(), null);
		}
		return dataSetService.getUserDataSet(userInfo.getUserId(), pageNumber, pageSize, dataSetType);
	}

	@ApiOperation(value="公开数据集列表", notes="项目创建时选择公开数据集,不包含其本人公开的")
	@GetMapping(value = "/optionalDataSetExceptOwn")
	public Response<PageInfo> optionalDataSetExceptOwn(
						@ApiParam(value = "当前页", required = false) @RequestParam(required = false) Integer pageNumber,
						@ApiParam(value = "每页条数", required = false) @RequestParam(required = false) Integer pageSize,
						@ApiParam(value = "搜索内容") @RequestParam(required = false)  Long categoryId,
														 HttpServletRequest request) {
		logger.info("searchPublicDataSetList param: pageNumber is {}, pageSize is {}, categoryId is {}", pageNumber, pageSize, categoryId);

		// 默认分页条件设置
		if(pageNumber == null || pageNumber < Constant.DEFAULT_PAGE_NUMBER) {
			pageNumber = Constant.DEFAULT_PAGE_NUMBER;
		}
		if(pageSize == null || pageSize < Constant.DEFAULT_PAGE_NUMBER) {
			pageSize = Constant.DEFAULT_PAGE_SIZE;
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}
		return dataSetService.optionalDataSetExceptOwn(pageNumber, pageSize, categoryId, userInfo);
	}

    @ApiOperation(value="获取用户是否关注数据集", notes="获取用户身份关注数据集")
    @GetMapping(value = "/getUserAttentionStatus")
    public Response<DataSetAttentionInfo> getUserAttentionStatus(
                            @ApiParam(value = "数据集ID", required = true) @RequestParam Long datasetId,
                            HttpServletRequest request) {

        logger.info("getUserAttentionStatus param: datasetId is {}", datasetId);

		if(datasetId == null){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getDesc(), null);
		}

        String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
        if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
            return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
        }
        return dataSetService.getUserAttentionStatus(datasetId, userInfo);
    }

	@ApiOperation(value="公开数据集列表", notes="项目创建时选择公开数据集,不包含其本人公开的和关注的")
	@GetMapping(value = "/optionalDataSetExceptOwnAndAttention")
	public Response<PageInfo> optionalDataSetExceptOwnAndAttention(
			@ApiParam(value = "当前页", required = false) @RequestParam(required = false) Integer pageNumber,
			@ApiParam(value = "每页条数", required = false) @RequestParam(required = false) Integer pageSize,
			HttpServletRequest request) {
		logger.info("optionalDataSetExceptOwnAndAttention param: pageNumber is {}, pageSize is {}", pageNumber, pageSize);

		// 默认分页条件设置
		if(pageNumber == null || pageNumber < Constant.DEFAULT_PAGE_NUMBER) {
			pageNumber = Constant.DEFAULT_PAGE_NUMBER;
		}
		if(pageSize == null || pageSize < Constant.DEFAULT_PAGE_NUMBER) {
			pageSize = Constant.DEFAULT_PAGE_SIZE;
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}
		return dataSetService.optionalDataSetExceptOwnAndAttention(pageNumber, pageSize, userInfo);
	}
	
	@ApiOperation(value="数据集是否公开给个人用户", notes="数据集是否公开给个人用户")
	@GetMapping(value = "/checkDataSetPublicPersonFlag")
	public Response<Boolean> checkDataSetPublicPersonFlag(
			@ApiParam(value = "数据集ID", required = true) @RequestParam Long datasetId,
			HttpServletRequest request) {

		logger.info("getUserAttentionStatus param: datasetId is {}", datasetId);

		if(datasetId == null){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getDesc(), null);
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}
		return dataSetService.checkDataSetPublicPersonFlag(datasetId);
	}

	@ApiOperation(value="数据集公开给个人用户列表", notes="数据集公开给个人用户列表")
	@GetMapping(value = "/getDataSetSharingUserList")
	public Response<DataSetSharingUserDto> getDataSetSharingUserList(
					@ApiParam(value = "数据集ID", required = true) @RequestParam Long datasetId,
					HttpServletRequest request) {

		logger.info("getUserAttentionStatus param: datasetId is {}", datasetId);

		if(null == datasetId){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getDesc(), null);
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}
		return dataSetService.getDataSetSharingUserList(datasetId, userInfo);
	}

	@ApiOperation(value="获取数据集简介", notes="获取数据集简介")
	@GetMapping(value = "/getDataSetConfig")
	public Response<String> getDataSetConfig(
			@ApiParam(value = "数据集ID", required = true) @RequestParam Long datasetId,
			HttpServletRequest request) {

		logger.info("getDataSetConfig param: datasetId is {}", datasetId);

		if(null == datasetId){
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getSeq(),
					DataSetEnum.DATASET_ID_IS_EMPTY_ERROR.getDesc(), null);
		}

		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(), DataSetEnum.GET_DATASET_ERROR.getDesc(), null);
		}

		return dataSetService.getDataSetProfile(datasetId);
	}
}
